<template>
  <div class="employees-container">
    <div class="app-container">

      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export-excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber', order: 'descending'}">
          <el-table-column label="序号" type="index" :index="hIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="头像" prop="staffPhoto">

            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" style="width : 80px"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id='+scope.row.id)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
          </el-table-column></el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="pageSize"
            :page-sizes="[2,5,10]"
            :current-page="page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹框 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <AddorEdit v-if="showDialog" @close="showDialog=false" @update-empolyee="hUpdateEmpolyee" />
      </el-dialog>
      <!-- 分配角色弹框 -->
      <el-dialog :visible.sync="showDialogRole" title="分配角色">
        <AssignRole v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole'
import AddorEdit from './empDialog'
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import EmployeeEnum from '@/constant/employees'

export default {
  name: 'EmployeesContainer',
  components: { AddorEdit, AssignRole },
  data() {
    return {
      showDialogRole: false, // 分配角色弹框
      showDialog: false,
      list: [],
      page: 1, // 当前页码
      pageSize: 5, // 每页几条
      total: 0, // 总共数据条数
      bookType: 'xlsx',
      filename: '人资员工列表',
      autoWidth: true,
      curEmployeId: ''// 当前员工编号
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const { data } = await getEmployeeList(this.page, this.pageSize)
        console.log(data)
        this.list = data.data.rows
        this.total = data.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    formatEmployment(id) {
      // 从hireType中 通过id找到对应的元素的value
      const item = EmployeeEnum.hireType.find(item => item.id === id)
      if (item) {
        return item.value
      } else {
        return '位置'
      }
    },
    // 会自动接收当前点击的页码
    handleCurrentChange(curPage) {
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    handleSizeChange(curSize) {
      this.page = 1
      // 1. 更新每页的条数
      this.pageSize = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 序号
    hIndex(index) {
      return index + 1 + (this.page - 1) * this.pageSize
    },
    // 封装删除函数
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)

        // 重发请求
        this.loadEmployee()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    // 删除
    hDel(id) {
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
        this.$message.success('删除成功')
        // 加载
        this.loadEmployeeList()
      }).catch(() => {})
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.pageSize)
      this.loadEmployeeList()
    },
    // excel导出
    async handleDownload() {
      this.downloadLoading = true
      // 打印全部数据 重发请求 请求全部数据
      const res = await getEmployeeList(this.page, this.total)
      console.log(res)
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = []

        const list = res.data.data.rows
        // 调用函数修改数据
        const data = this.formatJson(list, tHeader)
        excel.export_json_to_excel({
          header: data.tHeader,
          data: data.list,
          // 导出文件名
          filename: this.filename,
          // 视图宽是否自适应 为boolean值 默认true
          autoWidth: this.autoWidth,
          // 导出文件type 默认'xlsx'
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    // 封装函数用于修改excel导出数据（修饰为可用数据）
    formatJson(list, tHeader) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 省略了map的return
      list = list.map(item => Object.keys(map).map(key => item[key]))
      tHeader = Object.values(map)
      return { list, tHeader }
    },
    // 分配角色
    hAssignRole({ id }) {
      // console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
    }
  }
}
</script>

<style>

</style>
